#include "pdfpagemanager.h"
#include "unifiedcachemanager.h"
#include "fileidentitymanager.h"
#include <QPainter>
#include <QDebug>
#include <QFont>
#include <QFontMetrics>
#include <QTextOption>
#include <QApplication>
PDFPageManager::PDFPageManager(QObject *parent)
    : QObject(parent)
    , m_cacheManager(nullptr)
{
}
PDFPageManager::~PDFPageManager()
{
}
void PDFPageManager::setCacheManager(UnifiedCacheManager* cacheManager)
{
    m_cacheManager = cacheManager;
}
QList<QImage> PDFPageManager::generateFinalPDFPages(const QList<FileInfo>& files,
                                                   const OutputSettings& settings)
{
    QList<QImage> finalPages;
    // 1. 生成封面页（如果启用）
    if (settings.coverPage.enabled) {
        QImage coverPage = generateCoverPage(settings);
        if (!coverPage.isNull()) {
            finalPages.append(coverPage);
            emit pageGenerationProgress(1, calculateTotalPages(files, settings),
                                      tr("生成封面页"));
        }
    }
    // 2. 生成所有内容页（每个文件使用自己的布局模式）
    for (const FileInfo& fileInfo : files) {
        // 转换布局模式：int -> LayoutMode
        LayoutMode fileLayoutMode;
        switch (fileInfo.layoutMode) {
            case 1: fileLayoutMode = LayoutMode::SingleColumn; break;
            case 2: fileLayoutMode = LayoutMode::TwoColumns; break;
            case 3: fileLayoutMode = LayoutMode::ThreeColumns; break;
            default: fileLayoutMode = LayoutMode::SingleColumn; break;
        }
        // 每个文件单独处理，使用文件自己的布局模式
        QList<FileInfo> singleFileList;
        singleFileList.append(fileInfo);
        QList<QImage> filePages = generateContentPages(singleFileList, fileLayoutMode);
        finalPages.append(filePages);
    }
    emit pageGenerationProgress(finalPages.size(), finalPages.size(), tr("页面生成完成"));
    return finalPages;
}
QImage PDFPageManager::generateCoverPage(const OutputSettings& settings)
{
    // 创建A4尺寸的封面页
    QImage coverPage(A4_WIDTH, A4_HEIGHT, QImage::Format_RGB32);
    coverPage.fill(Qt::white);
    QPainter painter(&coverPage);
    painter.setRenderHint(QPainter::Antialiasing);
    // 设置页面边距
    int margin = MARGIN_SIZE;
    QRect contentRect(margin, margin, A4_WIDTH - 2 * margin, A4_HEIGHT - 2 * margin);
    // 绘制标题
    if (!settings.coverPage.title.isEmpty()) {
        painter.setFont(settings.coverPage.titleFont);
        QRect titleRect = contentRect;
        titleRect.setHeight(contentRect.height() / 4);
        painter.drawText(titleRect, Qt::AlignCenter | Qt::TextWordWrap,
                        settings.coverPage.title);
    }
    // 绘制副标题
    if (!settings.coverPage.subtitle.isEmpty()) {
        painter.setFont(settings.coverPage.subtitleFont);
        QRect subtitleRect = contentRect;
        subtitleRect.setTop(contentRect.height() / 4);
        subtitleRect.setHeight(contentRect.height() / 6);
        painter.drawText(subtitleRect, Qt::AlignCenter | Qt::TextWordWrap,
                        settings.coverPage.subtitle);
    }
    // 绘制作者
    if (!settings.coverPage.author.isEmpty()) {
        painter.setFont(settings.coverPage.authorFont);
        QRect authorRect = contentRect;
        authorRect.setTop(contentRect.height() * 3 / 4);
        authorRect.setHeight(contentRect.height() / 8);
        painter.drawText(authorRect, Qt::AlignCenter,
                        tr("作者: %1").arg(settings.coverPage.author));
    }
    // 绘制日期
    if (!settings.coverPage.date.isEmpty()) {
        painter.setFont(settings.coverPage.dateFont);
        QRect dateRect = contentRect;
        dateRect.setTop(contentRect.height() * 7 / 8);
        painter.drawText(dateRect, Qt::AlignCenter,
                        settings.coverPage.date);
    }
    painter.end();
    return coverPage;
}
QList<QImage> PDFPageManager::generateContentPages(const QList<FileInfo>& files,
                                                  LayoutMode mode)
{
    QList<QImage> allContentPages;
    // 逐个处理文件
    for (int fileIndex = 0; fileIndex < files.size(); ++fileIndex) {
        const FileInfo& fileInfo = files[fileIndex];
        emit pageGenerationProgress(fileIndex + 1, files.size(),
                                  tr("处理文件: %1").arg(fileInfo.fileName));
        // 加载原始页面
        QList<QImage> originalPages = loadOriginalPages(fileInfo.filePath);
        if (originalPages.isEmpty()) {
            continue;
        }
        // 应用布局模式，生成组合页面
        QList<QImage> layoutPages = rearrangePagesForColumns(originalPages, mode);
        allContentPages.append(layoutPages);
    }
    return allContentPages;
}
QList<QImage> PDFPageManager::loadOriginalPages(const QString& filePath)
{
    QList<QImage> originalPages;
    if (!m_cacheManager) {
        return originalPages;
    }
    // 获取文件标识和页数
    QString fileIdentity = m_cacheManager->getFileIdentityForPath(filePath);
    int totalPages = m_cacheManager->getCachedPageCount(filePath);
    if (totalPages <= 0) {
        return originalPages;
    }
    // 加载所有页面（不像MainWindow的懒加载，这里需要所有页面）
    for (int i = 0; i < totalPages; ++i) {
        QImage page = m_cacheManager->loadFromCache(fileIdentity, i);
        if (!page.isNull()) {
            originalPages.append(page);
        } else {
            // 对于PDF生成，我们不能有占位符，所以跳过这页
            // 或者创建一个错误页面
            QImage errorPage(800, 1200, QImage::Format_RGB32);
            errorPage.fill(Qt::white);
            QPainter painter(&errorPage);
            painter.drawText(errorPage.rect(), Qt::AlignCenter,
                           tr("页面 %1 加载失败").arg(i + 1));
            painter.end();
            originalPages.append(errorPage);
        }
        // 每处理10页处理一次事件，保持响应性
        if (i % 10 == 0) {
            emit pageGenerationProgress(i + 1, totalPages,
                                      tr("加载页面 %1/%2").arg(i + 1).arg(totalPages));
            QApplication::processEvents();
        }
    }
    return originalPages;
}
QImage PDFPageManager::generateCompositePage(const QList<QImage>& sourcePages,
                                            LayoutMode mode)
{
    if (sourcePages.isEmpty()) {
        return QImage();
    }
    // 单栏模式直接返回第一页
    if (mode == LayoutMode::SingleColumn) {
        return sourcePages.first();
    }
    // 实现双栏和三栏的组合逻辑
    // 创建A4尺寸的组合页面
    QImage compositePage(A4_WIDTH, A4_HEIGHT, QImage::Format_RGB32);
    compositePage.fill(Qt::white);
    QPainter painter(&compositePage);
    painter.setRenderHint(QPainter::Antialiasing);
    int margin = MARGIN_SIZE;
    int availableWidth = A4_WIDTH - 2 * margin;
    int availableHeight = A4_HEIGHT - 2 * margin;
    if (mode == LayoutMode::TwoColumns) {
        // 双栏布局：两页并排
        int columnWidth = (availableWidth - COLUMN_SPACING) / 2;
        int columnHeight = availableHeight;
        for (int i = 0; i < qMin(sourcePages.size(), 2); ++i) {
            QImage scaledPage = sourcePages[i].scaled(
                columnWidth, columnHeight,
                Qt::KeepAspectRatio, Qt::SmoothTransformation);
            int x = margin + i * (columnWidth + COLUMN_SPACING);
            int y = margin + (columnHeight - scaledPage.height()) / 2; // 垂直居中
            painter.drawImage(x, y, scaledPage);
        }
    } else if (mode == LayoutMode::ThreeColumns) {
        // 三栏布局：三页并排
        int columnWidth = (availableWidth - 2 * COLUMN_SPACING) / 3;
        int columnHeight = availableHeight;
        for (int i = 0; i < qMin(sourcePages.size(), 3); ++i) {
            QImage scaledPage = sourcePages[i].scaled(
                columnWidth, columnHeight,
                Qt::KeepAspectRatio, Qt::SmoothTransformation);
            int x = margin + i * (columnWidth + COLUMN_SPACING);
            int y = margin + (columnHeight - scaledPage.height()) / 2; // 垂直居中
            painter.drawImage(x, y, scaledPage);
        }
    }
    painter.end();
    return compositePage;
}
QList<QImage> PDFPageManager::rearrangePagesForColumns(const QList<QImage>& originalPages,
                                                      LayoutMode mode)
{
    QList<QImage> result;
    if (originalPages.isEmpty()) {
        return result;
    }
    switch (mode) {
        case LayoutMode::SingleColumn:
            // 单栏模式：直接返回原始页面
            result = originalPages;
            break;
        case LayoutMode::TwoColumns:
            result = rearrangeForTwoColumns(originalPages);
            break;
        case LayoutMode::ThreeColumns:
            result = rearrangeForThreeColumns(originalPages);
            break;
    }
    return result;
}
QList<QImage> PDFPageManager::rearrangeForTwoColumns(const QList<QImage>& originalPages)
{
    QList<QImage> result;
    // 两页合并成一页
    for (int i = 0; i < originalPages.size(); i += 2) {
        QList<QImage> pagePair;
        pagePair.append(originalPages[i]);
        if (i + 1 < originalPages.size()) {
            pagePair.append(originalPages[i + 1]);
        }
        QImage compositePage = generateCompositePage(pagePair, LayoutMode::TwoColumns);
        if (!compositePage.isNull()) {
            result.append(compositePage);
        }
    }
    return result;
}
QList<QImage> PDFPageManager::rearrangeForThreeColumns(const QList<QImage>& originalPages)
{
    QList<QImage> result;
    // 三页合并成一页
    for (int i = 0; i < originalPages.size(); i += 3) {
        QList<QImage> pageTriple;
        pageTriple.append(originalPages[i]);
        if (i + 1 < originalPages.size()) {
            pageTriple.append(originalPages[i + 1]);
        }
        if (i + 2 < originalPages.size()) {
            pageTriple.append(originalPages[i + 2]);
        }
        QImage compositePage = generateCompositePage(pageTriple, LayoutMode::ThreeColumns);
        if (!compositePage.isNull()) {
            result.append(compositePage);
        }
    }
    return result;
}
int PDFPageManager::calculateTotalPages(const QList<FileInfo>& files,
                                      const OutputSettings& settings)
{
    int totalPages = 0;
    // 封面页
    if (settings.coverPage.enabled) {
        totalPages += 1;
    }
    // 内容页（根据布局模式计算）
    // 注意：这里暂时按单栏模式计算，实际应该从MainWindow获取当前布局模式
    // TODO: 从MainWindow获取当前布局模式进行正确计算
    for (const FileInfo& file : files) {
        int filePages = file.cachedPageCount > 0 ? file.cachedPageCount : file.pageCount;
        // 单栏模式：页数不变
        // 双栏模式：页数/2（向上取整）
        // 三栏模式：页数/3（向上取整）
        // 暂时使用单栏模式计算，完整实现需要布局模式参数
        totalPages += filePages;
    }
    return totalPages;
}
QImage PDFPageManager::renderVerticalFlowLayout(const QList<QList<QImage>>& columnImages,
                                              const QList<int>& columnImageWidths,
                                              int columns, int columnWidth, int columnSpacing,
                                              int marginTop, int marginLeft, int marginBottom,
                                              int a4Width, int a4Height, int availableHeight)
{
    // TODO: 实现垂直流布局渲染
    // 这是从MainWindow迁移过来的复杂布局逻辑
    QImage result(a4Width, a4Height, QImage::Format_RGB32);
    result.fill(Qt::white);
    return result;
}